package com.ge.chapter03webflux.controller;

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(@RequestParam(value = "key", defaultValue = "default") String key) {
        return "Hello World!!! key = " + key;
    }

    @GetMapping("/monoHello")
    public Mono<String> helloMono(@RequestParam(value = "key", defaultValue = "default") String key) {
        return Mono.just("Hello World!!! key = " + key);
    }

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sseTest() {
        return Flux.range(1, 10)
                .map(i -> "SSE TEST: " + i)
                // 设定时间间隔推送数据
                .delayElements(Duration.ofMillis(1000));
    }

    @GetMapping(value = "/sse2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sseTest2() {
        return Flux.range(1, 10)
                .map(i -> ServerSentEvent.builder("SSE TEST: " + i)
                        .id("" + i)
                        .comment("comment: " + i)
                        .event("EVENT")
                        .build())
                .delayElements(Duration.ofMillis(1000));
    }
}
